# -*- coding: utf-8 -*-

import socket
import threading

class ClientThread(threading.Thread):
    working = True
    def __init__(self, channel, details):
        self._channel = channel
        self._details = details
        threading.Thread.__init__(self)
    def run(self):
        self.working = True
        print 'Received connection:', self._details[0]
        self._channel.setblocking(0)
        buffer = ''
        while self.working:
            try:
                str = self._channel.recv(1024)
                if str == '':
                    break
                buffer = buffer + str
                print buffer
                end = '\n'
                end_pos = buffer.find(end)
                if end_pos != -1:
                    msg = buffer[0:end_pos + len(end)]
                    buffer = buffer[end_pos + len(end):len(buffer)]
                    self.process_message(msg)
            except:
                pass
        self._channel.close()
        print 'Closed connection:', self._details[0]
    def process_message(self, msg):
        print msg

class CPSServerListener(threading.Thread):
    working = True
    def __init__(self, port):
        self._port = port
        threading.Thread.__init__(self)
    def run(self):
        self.working = True
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind(('', self._port))
        server.settimeout(1)
        server.listen(5)
        while self.working:
            try:
                (channel, details) = server.accept()
                ClientThread(channel, details).start()
            except socket.timeout:
                pass
        server.close()

server = CPSServerListener(31330)
server.run()